<template>
  <div class="warpper">
    <div class="toolbar">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" label-width="auto" label-position="right">
        <el-form-item label="Name">
          <el-input v-model="searchForm.name" @keyup.enter.native="search" placeholder="Enter Name"
            style="width: 108%;">
          </el-input>
        </el-form-item>
        <el-form-item label="Status" prop="status">
          <el-select v-model="searchForm.status" placeholder="Select status">
            <el-option v-for="item in status" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="Belonging Sales" prop="belongingsales" style="margin-left:48px;">
          <el-select v-model="searchForm.belongingsales" placeholder="Select Belonging Sales">
            <el-option v-for="item in belongingsales" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button @click="find()" plain style="margin-left: 24px;">Search</el-button>
          <el-button type="primary" v-permission="['warehouses.store']" plain @click="warehouseadd">+ New</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table">
      <el-table :data="tableData" size="small" stripe border style="width: 100%">
        <el-table-column prop="name" label="Name" min-width="150" align="center" sortable />
        <el-table-column prop="belongingsales" label="Belonging Sales" style="width: 480px;" sortable>
          <template slot-scope="scope">
            <span>{{ scope.row.belongingsales }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="total_qty" label="QTY" style="width: 460px;" sortable>
          <template slot-scope="scope">
            <span>{{scope.row.total_qty}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="total_tatil" label="Amount(S$)" style="width: 460px;" sortable>
          <template slot-scope="scope">
            <span>{{scope.row.total_tatil}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="Status" min-width="150" align="center" sortable />
        <el-table-column prop="adminame" label="Staff" min-width="150" align="center" />
        <el-table-column prop="created_at" label="Created Time" min-width="200" align="center" sortable>
          <template v-slot="scope">
            <span>{{ scope.row.created_at | showDateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="240">
          <template slot-scope="scope">
            <el-button size="mini" v-permission="['warehouses.show']" plain @click="edit(scope.row.id)">view</el-button>
            <el-button size="mini" v-permission="['warehouses.update']" plain
              @click="edit(scope.row.id)">edit</el-button>

            <el-button size="mini" v-permission="['warehouses.destroy']" v-if="scope.row.status=='Disable'"
              type="danger" @click="editstatus(scope.row.id,'Normal')">Enable</el-button>
            <el-button size="mini" v-if="scope.row.status=='Normal'" plain type="danger"
              @click="editstatus(scope.row.id,'Disable')">Disable</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page">
      <el-pagination v-if="isPaginate" background :current-page="page.current_page" :page-sizes="page.sizes"
        :page-size="page.per_page" layout="prev, pager, next" :total="page.total" @size-change="sizeChange"
        @current-change="currentChange" />
    </div>

  </div>
</template>

<script>
  import CURD from "@/mixin/CURD";
  import {
    index as adminindex
  } from "@/api/admin";
  import {
    index,
    update
  } from "@/api/warehouse";
  export default {
    mixins: [CURD],
    name: "warehouse_index",
    data() {
      return {
        searchForm: {
          status: null,
          belongingsales: null
        },
        module: "warehouse",
        isPaginate: true,
        status: [{
            id: null,
            name: "All",
          },
          {
            id: "Enable",
            name: "Enable",
          }, {
            id: "Disable",
            name: "Disable",
          }
        ],
        belongingsales: [{
          id: null,
          name: "All",
        }],
      };
    },
    watch: {
    // 监听路由变化
    '$route': {
      handler: function(to, from) {
        // 当路由发生变化时重新获取数据
        this.fetchData()
      },
      immediate: true
    }
  },
    async created() {

      try {
        const {
          data
        } = await adminindex(1, 100, {
          usertype: 1
        });
        this.belongingsales = data.map(item => ({
          id: item.nickname, // 将 nickname 的值赋给 id
          name: item.nickname // 将 nickname 的值赋给 name
        }));
        this.belongingsales.unshift({
          id: null,
          name: 'All'
        });
      } catch (error) {
        console.error('Failed to fetch staff:', error);
      }
      await this.fetchData();
      console.log("dfsdfsdffffffffffff")
    },
    methods: {
      async fetchData() {
          let {
            index
          } = require(`@/api/${this.module}`);
          const res = await index(
            this.page.current_page,
            this.page.per_page,
            this.searchForm
          );
          if (
            res.data instanceof Object &&
            typeof this.transfromData === "function"
          ) {
            let data = this.transfromData(res.data);
            this.tableData = data;
          } else {
            this.tableData = res.data;
          }
          let {
            rules
          } = require(`@/model/${this.module}`);
          this.rules = rules;
          if (res.meta) {
            // 分页
            res.meta.per_page = parseInt(res.meta.per_page);
            this.page = Object.assign(this.page, res.meta);
          } else {
            this.isPaginate = false; // 不分页
          }
      },
      warehouseadd() {
        this.$router.push({
          path: '/warehouse/warehouseadd',
          query: {
            id: null
          }
        })
      },
      edit(id) {
        this.$router.push({
          path: '/warehouse/editwarehouse',
          query: {
            id: id
          }
        })
      },
      async editstatus(id, statusdata) {
        try {
          await this.$confirm("This operation will permanently Save status. Do you want to continue?", "prompt", {
            confirmButtonText: "Confirm",
            cancelButtonText: "Cancel",
            type: "warning"
          });
          let {
            info
          } = await update({
            id: id,
            action: "status",
            status: statusdata
          });
          this.$message.success(info);
          await this.fetchData();
        } catch (error) {
          this.$message({
            type: "info",
            message: "Cancelled save"
          });
        }
      },
    }
  };
</script>

<style>
  .table,
  .toolbar,
  .page {
    margin: 20px;
  }

  .toolbar {
    margin-top: 10px;
    padding: 5px;
  }

  .table {
    margin-bottom: 10px;
  }

  .page {
    margin-top: 10px;
    text-align: center;
  }

  .avatar {
    width: 50%;
    height: 50%;
    display: block;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
</style>
